package com.katze.boot.system.controller;

import com.katze.boot.plugins.redis.RedisInfo;
import com.katze.boot.plugins.redis.operations.RedisOperations;
import com.katze.boot.plugins.security.annotations.RestControllerMapping;
import com.katze.boot.plugins.security.annotations.RestRequestMapping;
import com.katze.common.Message;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.data.redis.connection.RedisServerCommands;
import org.springframework.data.redis.core.RedisCallback;

import java.util.*;

@RestControllerMapping("/redis")
public class RedisController {

    @Resource
    private RedisOperations<String> operations;

    @RestRequestMapping(value = "info", skip = true)
    public Message getRedisInfo() {
        Properties properties = operations.select(-1, o-> o.execute((RedisCallback<Properties>) RedisServerCommands::info));
        List<RedisInfo> infoList = new ArrayList<>();
        for (Object o : properties.keySet()) {
            infoList.add( new RedisInfo(o.toString(), properties.get(o).toString()));
        }
       return Message.ok().data(infoList);
    }

    @RestRequestMapping(value = "/keysSize", skip = true)
    public Message getKeysSize() {
        Long dbSize = operations.select(-1, o-> o.execute(RedisServerCommands::dbSize));
        Map<String, Object> map = new HashMap<>();
        map.put("create_time", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        map.put("dbSize", dbSize);
        return Message.ok().data(map);
    }

    @RestRequestMapping(value = "/memoryInfo", skip = true)
    public Message getMemoryInfo() {
        Properties properties = operations.select(-1, o-> o.execute((RedisCallback<Properties>) RedisServerCommands::info));
        Map<String, Object> map = new HashMap<>();
        map.put("used_memory", Long.parseLong(properties.getProperty("used_memory")));
        map.put("create_time", System.currentTimeMillis());
        return Message.ok().data(map);
    }
}
